package cn.onesdream.app.api.service.Impl;

import cn.onesdream.app.api.service.CollectionService;
import cn.onesdream.app.common.exception.ServiceException;
import cn.onesdream.app.dao.entity.Collection;
import cn.onesdream.app.dao.mapper.CollectionMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * @author WangShiyu
 * @date 2021/3/20 13:54
 */
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements CollectionService {

    @Override
    public void deleteCollectionByObjectId(Byte typeId, Integer objectId, Integer userId) throws ServiceException {
        Collection collection;
        QueryWrapper<Collection> wrapper = new QueryWrapper<>();
        wrapper.eq("type_id",typeId).eq("object_id",objectId).eq("user_id",userId);
        collection = baseMapper.selectOne(wrapper);
        if (collection == null){
            throw new ServiceException("不存在该数据！");
        }
        else {
            baseMapper.delete(wrapper);
        }
    }

    @Override
    public void deleteCollection(Integer collectionId, Integer userId) throws ServiceException {
        Collection collection;
        collection = baseMapper.selectById(collectionId);
        if (collection.getUserId() == userId){
            baseMapper.deleteById(collectionId);}
        else {
            throw new ServiceException("不能删除别人的收藏内容！");
        }
    }

    @Override
    public List<Collection> getCollection(Integer userId) {
        QueryWrapper<Collection> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void collect(Integer userId, Byte typeId, Integer objectId) throws ServiceException {
        Collection collection = baseMapper.getLostCollectionById(userId, typeId, objectId);
        if(collection == null){
            collection = new Collection();
            collection.setUserId(userId);
            collection.setTypeId(typeId);
            collection.setObjectId(objectId);
            baseMapper.insert(collection);
        }
        else {
            collection.setActive((byte) 1);
            baseMapper.addLostCollection(collection);
        }
    }
}
